/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.core;

import java.util.List;

import com.cqcis.uip.base.logadaptor.LogConfiguration;

/**
 * 带日志服务的运行代理
 * 
 * @author huangmy
 * @date   2009-3-31
 */
public class RunnaleWrapper implements Runnable {
	private Runnable runnable; // proxyed
	private RegisteredServiceContext serviceContext;
	
	public RunnaleWrapper(RegisteredServiceContext serviceContext) {
		if (serviceContext == null) {
			throw new NullPointerException("serviceContext can't be null");
		}
    	this.serviceContext = serviceContext;
    }
	
	public RunnaleWrapper(RegisteredServiceContext serviceContext, Runnable runnable) {
		if (serviceContext == null) {
			throw new NullPointerException("serviceContext can't be null");
		}
		if (runnable == null) {
			throw new NullPointerException("runnable can't be null");
		}
		
    	this.serviceContext = serviceContext;
    	this.runnable = runnable;
    }
	
	public final void run() {
		List<LogConfiguration> oldLogConfigr = serviceContext.getLogService().getLogConfiguration(Thread.currentThread());;
		String oldThreadName = Thread.currentThread().getName();
		
    	try {
			LogConfiguration logConfig = serviceContext.getRegisteredService().getLogConfiguration();
			Thread.currentThread().setName(serviceContext.getRegisteredService().getName());					
			serviceContext.getLogService().unregister(Thread.currentThread());
			serviceContext.getLogService().register(logConfig);
			
			if (this.runnable != null) {
				this.runnable.run();
			}
		} finally {						
			if (oldLogConfigr != null) {
				serviceContext.getLogService().unregister();
				for (LogConfiguration config : oldLogConfigr) {
					serviceContext.getLogService().register(config);
				}
			} else {
				serviceContext.getLogService().unregister();
			} 
			
			Thread.currentThread().setName(oldThreadName);
		}
	}

	public final void setRunnable(Runnable runnable) {
		this.runnable = runnable;
	}
}
